// pages/user/user.js
import {
    Address
} from './selAddress-model.js';

const app = getApp()
const $address = new Address()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        dialogShow: false,
        threeArea: {
            provice: null,
            city: null,
            area: null
        },
        hasCity: true,
        hasArea: true,
        editAddress: null,
        editRegion: [],
        addressList: null,
        isShowPopup: false,
        tips: '',
        toggleWord: '新增',
        editId: '',
        loadDone: false,
        editStatusReset: false,
        addressId: '',
        orderId: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options, options.orderId, options.addressId)
        let that = this


        this.setData({
            orderId: options.orderId,
            addressId: options.addressId
        })
        wx.showLoading({
            title: '加载中',
        })


        $address.getUserAddress({
            data: {}
        }, res => {
            let status = res.status;
            let data = res.data;
            wx.hideLoading()
            if (status) {
                data && data.forEach(val => {
                    val.checked = false
                })
                if (options.addressId) {
                    data.forEach((val, i) => {
                        if (val.id == options.addressId) {
                            val.checked = true
                        }
                    })
                }
                that.setData({
                    addressList: data,
                    loadDone: true
                })
            } else {
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })

            }
        })
    },

    preventD(e) {
        return;
    },
    // 省选择
    proviceChange(e) {
        console.log(e.detail.value)
        let val = e.detail.value
        let provice = this.data.threeArea.provice[val]
        let that = this
        let params = {
            "data": {
                "pid": provice.id
            }
        }
        $address.getThree(params, res => {
            if (res.status) {
                that.setData({
                    'threeArea.city': res.data,
                    'editRegion[1]': '',
                    'editRegion[2]': '',
                })
            }
        })
        this.setData({
            'editRegion[0]': {
                id: provice.pid,
                name: provice.name,
                index: val
            },
            hasCity: false,
            hasArea: true

        })
        if (this.data.toggleWord == '编辑') {
            this.setData({
                'editAddress.detailedAddress': '',
                editStatusReset: true
            })
        }
    },
    // 市选择
    cityChange(e) {
        console.log(e.detail.value)
        let that = this
        let val = e.detail.value
        let city = this.data.threeArea.city[val]
        let params = {
            "data": {
                "pid": city.id
            }
        }
        $address.getThree(params, res => {
            if (res.status) {
                that.setData({
                    'threeArea.area': res.data,
                    'editRegion[2]': '',

                })
            }
        })
        this.setData({
            'editRegion[1]': {
                id: city.pid,
                name: city.name,
                index: val
            },
            hasArea: false,
        })
        if (this.data.toggleWord == '编辑') {
            this.setData({
                'editAddress.detailedAddress': '',
                editStatusReset: true
            })
        }
    },
    // 区域选择
    areaChange(e) {
        console.log(e.detail.value)
        let val = e.detail.value
        let area = this.data.threeArea.area[val]

        this.setData({
            'editRegion[2]': {
                id: area.pid,
                name: area.name,
                index: val
            },
        })
        if (this.data.toggleWord == '编辑') {
            this.setData({
                'editAddress.detailedAddress': '',
                editStatusReset: true
            })
        }
    },
    // 设置默认地址
    setDefault(e) {
        let id = e.currentTarget.dataset.id
        let that = this
        let params = {
            data: {
                "id": "" + id,
                "defaultOptions": "1"
            }
        }
        console.log(params)
        this.commonUpdate(params, '确认设置为默认地址吗？', '设置成功')
    },
    edit(e) {
        let province, city, area;
        let id = e.currentTarget.dataset.id
        let data = this.data
        wx.navigateTo({
            url: '/pages/editAddress/editAddress?type=sel&orderId=' + data.orderId + '&addressId=' + data.addressId + '&id=' + id,
        })
    },
    delete(e) {
        let id = e.currentTarget.dataset.id
        let that = this
        let params = {
            data: {
                "id": "" + id,
                "status": "1"
            }
        }
        console.log(params)
        this.commonUpdate(params, '确定删除吗？', '删除成功')
    },

    commonUpdate(params, content, title) {
        var that = this
        let data = this.data
        wx.showModal({
            title: '提示',
            content: content,
            success: function (res) {
                if (res.confirm) {
                    $address.updateUserAddress(params, res2 => {
                        console.log(res2)
                        let status = res2.status
                        if (status) {
                            wx.showToast({
                                title: title,
                                icon: 'success',
                                duration: 2000,
                                success() {
                                    setTimeout(() => {
                                        that.onLoad({
                                            orderId: data.orderId,
                                            addressId: data.addressId
                                        })
                                    }, 2000)
                                }
                            })
                        } else {
                            wx.hideLoading()
                            wx.showToast({
                                title: '服务器错误',
                                icon: 'none'
                            })
                        }
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    selAddress(e) {
        let id = $address.getDataSet(e, "id")
        let data = this.data
        let that = this
        let addressList = data.addressList
        addressList.forEach((val, i) => {
            if (val.id == id) {
                val.checked = true
            } else {
                val.checked = false

            }
        })
        this.setData({
            addressList: addressList
        })

        let params = {
            "data": {
                "orderId": '' + data.orderId,
                "userAddressId": '' + id

            }
        }
        $address.updateOrderAddress(params, res => {
            if (res.status) {
                setTimeout(() => {
                    var pagelist = getCurrentPages();
                    if (pagelist.length > 1) {
                        //获取上一个页面实例对象
                        var prePage = pagelist[pagelist.length - 2];
                        prePage.getBackAddressId(id);

                        wx.navigateBack({
                            delta: 1
                        })
                    }
                }, 300)
            } else {
                wx.showToast({
                    title: '选择失败，请重新选择地址',
                    icon: 'none'
                })
            }
        });

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },
    showAddAddress() {
        this.setData({
            dialogShow: true,
            toggleWord: '新增',
            editAddress: null,
            editRegion: null,
            hasCity: true,
            hasArea: true
        })
    },
    save() {
        this.cancel()
    },
    cancel() {
        this.setData({
            dialogShow: false
        })
    },
    bindRegionChange(data) {
        console.log(data)
        this.setData({
            'editRegion': data.detail.value
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        //this.onLoad()
        $address.getUserAddress({
            data: {
                "userId": (this.data.userInfo.id).toString()
            }
        }, res => {
            let status = res.status;
            let data = res.data;
            wx.hideLoading()
            wx.stopPullDownRefresh()
            if (status) {
                this.setData({
                    addressList: data,
                })
            } else {
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })
    },




})